package com.yanggu.kafka.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class KafkaProducerController {

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    @GetMapping("send/message")
    public void sendMessage(@RequestParam("message") String message) {
        System.out.println(kafkaTemplate.send("first", message));
    }

    @GetMapping("send/message2")
    public void sendMessage2(@RequestParam("message") String message) {
        kafkaTemplate.send("first", message).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {

            @Override
            public void onFailure(Throwable ex) {
                System.out.println("信息发送失败" + ex.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Object> result) {
                System.out.println("发送消息成功：" + result.getRecordMetadata().topic() + "-"
                        + result.getRecordMetadata().partition() + "-" + result.getRecordMetadata().offset());
            }
        });
    }

    @GetMapping("send/message3")
    //@Transactional(transactionManager = "kafkaTransactionManager", rollbackFor = RuntimeException.class)
    public void sendMessage3(@RequestParam("message") String message) {

        //声明事务, 后面报错消息不会发送出去
        //kafkaTemplate.executeInTransaction(operations -> {
        //    operations.send("first", message);
        //    throw new RuntimeException("fail");
        //});


        kafkaTemplate.send("first", message);
        throw new RuntimeException("fail");
    }

    @GetMapping("send/message4")
    public void sendMessage4(@RequestParam("message") String message) {
        System.out.println(kafkaTemplate.send("second", message));
    }

    @GetMapping("send/message5")
    public void sendMessage5(@RequestParam("message") String message) {
        System.out.println(kafkaTemplate.send("third", message));
    }

}
